<?php
	$id = $_POST['chat'];
	$text = htmlentities($_POST['text'],ENT_QUOTES);
	
	if ($_POST['editmsg'] != 0){
		PDO_Execute("UPDATE message SET text = \"$text\" WHERE id = ".$_POST['editmsg']);
		PDO_Execute("DELETE FROM urlpreview WHERE message_id = ".$_POST['editmsg']);
		PDO_Execute("DELETE FROM todo WHERE message_id = ".$_POST['editmsg']);
	} else {
		PDO_Execute("INSERT INTO message (chat_id,text,date) VALUES ($id,\"$text\",".time().");");
	}
	if ($_POST['editmsg'] != 0){
		$last_id = $_POST['editmsg'];
	} else {
		$last_id = PDO_FetchAll("SELECT id FROM message ORDER BY id DESC LIMIT 1")[0]['id'];
	}
	
	
	//url preview
	$regex = '/https?\:\/\/[^\" ]+/i';
	preg_match($regex, $_POST['text'], $matches);
	@$url = $matches[0];
	if (!empty($url)){
		$result = getMetaTags($url);

		$site = array();
		$site['name'] = getSiteName($url);


		@$site['title'] = (empty($result['openGraph']['title'])? $result['openGraph']['title'] : $result['twitterCards']['title']);
		if (empty($title)){
			$site['title'] = htmlentities(getPageTitle($url),ENT_QUOTES);
		}
		
		if(!empty($site['title'])){
			@$site['desc'] = htmlentities((empty($result['openGraph']['description'])? $result['openGraph']['description'] : $result['twitterCards']['description']),ENT_QUOTES);
			@$site['image'] = (empty($result['openGraph']['image'])? $result['openGraph']['image'] : $result['twitterCards']['image']);
			PDO_Execute("INSERT INTO urlpreview (message_id,url,site,title,desc,image) VALUES ($last_id,\"$url\",\"".$site['name']."\",\"".$site['title']."\",\"".$site['desc']."\",\"".$site['image']."\")");
		}

	}

	if (!empty($_FILES)){
		if ($_POST['editmsg'] != 0){
			PDO_Execute("DELETE FROM attachment WHERE message_id = ".$_POST['editmsg']);
		}
		$name = basename($_FILES["file"]["name"]);
		if($system['os'] == "w"){
			$target_file = ".\\tmp\\".$name;
		} else {
			$target_file = "./tmp/".$name;
		}
			
		if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
			$time = time();
			$size = filesize("$target_file");
			$type = $_FILES["file"]["type"];
			$preview = null;
			if (is_numeric(strpos($type,"image"))){

				if($_POST['compress'] == 'true'){
					$basename = $name;
					@$ext = end(explode(".",$basename));
					$fname = str_replace(".$ext","",$basename);
					$oname = time().".$ext";
					
					$path_prefix = ($system['os'] == "w") ? ".\\tmp\\" : "./tmp/";
					
					rename($target_file,$path_prefix.$oname);
					exec("convert \"{$path_prefix}$oname\" -resize \"1280x1280>\" -quality 85 \"{$path_prefix}$fname.jpg\"");
					exec("magick \"{$path_prefix}$oname\" -resize \"1280x1280\\>\" -quality 85 \"{$path_prefix}$fname.jpg\"");
					$file = file_get_contents("{$path_prefix}$fname.jpg");
					$target_file = "{$path_prefix}$fname.jpg";
					$type = "image/jpeg";
					$size = filesize("$target_file");
					unlink("{$path_prefix}$oname");

					$name = "$fname.jpg";
					
				} else {
				
					$file = file_get_contents("$target_file");
			
					if (filesize("$target_file") >= "100000"){
						if($system['os'] == "w"){
							exec("magick \"$target_file\" -resize \"1280x1280\\>\" -quality 80 prv.webp");
						} else {
							exec("convert \"$target_file\" -resize \"1280x1280>\" -quality 80 prv.webp");
							exec("magick \"$target_file\" -resize \"1280x1280\\>\" -quality 80 prv.webp");
						}
						$preview = file_get_contents("prv.webp");
					}
				
				}

			} else {
				exec("7z a $time.7z \"$target_file\"");
				unlink($target_file);
				$file = file_get_contents("$time.7z");
			}
			$file = base64_encode($file);
			$preview = base64_encode($preview);
			PDO_Execute("INSERT INTO attachment (message_id,name,type,size,content,preview) VALUES ($last_id,\"$name\",\"$type\",$size,\"$file\",\"$preview\")");
			
			@unlink("$time.7z");
			@unlink("$target_file");
			@unlink("prv.webp");
		}
	}
	
	if($_POST['changedDate'] == true){
		if ($_POST['editmsg'] != 0){
			PDO_Execute("DELETE FROM reminder WHERE message_id = ".$_POST['editmsg']);
		}
		$date = strtotime($_POST['date']);
		if ($date > time()){
			PDO_Execute("INSERT INTO reminder (message_id,date,active) VALUES ($last_id,$date,1)");
		}
	}
	
	$matches = [];
	preg_match_all('/^>>.*/m', html_entity_decode($text), $matches);
	
	if (!empty($matches[0])){
		$qry = array();
		foreach ($matches[0] as $match){
			$completed = "false";
			if(is_numeric(strpos($match,">>>"))){
				$completed = "true";
				$match = substr($match,1);
			}
			$todo = htmlentities(trim(str_replace(">","",$match)),ENT_QUOTES);
			$qry[] = "($last_id,\"$todo\",\"$completed\")";
		}
		//echo "INSERT INTO todo (message_id,text,completed) VALUES ".implode(",",$qry);
		PDO_Execute("INSERT INTO todo (message_id,text,completed) VALUES ".implode(",",$qry));
	}
?>
